<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品添加</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区 -->
    <el-card>
      <!-- 提示条 -->
      <el-alert title="添加商品页" type="info" center show-icon></el-alert>
      <!-- 步骤条 -->
      <el-steps :active="active - 0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- tab 栏 -->
      <!-- 使用 form 表单，来包裹 tab 栏 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-position="top">
        <el-tabs
          tab-position="left"
          v-model="active"
          :before-leave="changeTabs"
          @tab-click="clickTabs"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称：" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格：" prop="goods_price">
              <el-input v-model="addForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量：" prop="goods_weight">
              <el-input v-model="addForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量：" prop="goods_number">
              <el-input v-model="addForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量：" prop="goods_cat">
              <el-cascader
                v-model="addForm.goods_cat"
                :options="cateList"
                :props="cateProps"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item :label="item.attr_name" v-for="(item,i) in manyData" :key="i">
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  :label="element"
                  v-for="(element,i1) in item.attr_vals "
                  :key="i1"
                  border
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item :label="item.attr_name" v-for="(item,i) in onlyData" :key="i">
              <el-input type="text" v-model="item.attr_vals" />
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              :action="uploadUrl"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="headerObj"
              :on-success="successhandle"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="addForm.goods_introduce" />

            <el-button type="primary" @click="addFormHandle">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>

    <!-- 图片预览弹框 -->
    <el-dialog title="图片预览" :visible.sync="picDialogVisible" width="50%">
      <img :src="picPath" alt class="sbhh" />
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // tab 栏 与 步骤条，进度高亮绑定
      active: '',
      // 添加商品表单数据
      addForm: {
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        goods_cat: [],
        pics: [],
        goods_introduce: '',
        attrs: []
      },
      // 表单验证对象
      addFormRules: {
        goods_name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
        goods_price: [{ required: true, message: '请输入商品价格', trigger: 'blur' }],
        goods_weight: [{ required: true, message: '请输入商品重量', trigger: 'blur' }],
        goods_number: [{ required: true, message: '请输入商品内容', trigger: 'blur' }],
        goods_cat: [{ required: true, message: '请选择商品分类', trigger: 'blur' }]
      },
      // 所有商品信息
      cateList: [],
      // 配置级联选择器
      cateProps: {
        expandTrigger: 'hover',
        label: 'cat_name',
        value: 'cat_id',
        children: 'children'
      },
      // 动态参数数据
      manyData: [],
      // 静态属性
      onlyData: [],
      // 图片上传地址
      uploadUrl: 'http://127.0.0.1:8888/api/private/v1/upload',
      // 图片上传 请求头
      headerObj: {
        Authorization: window.sessionStorage.getItem('token')
      },
      // 控制图片弹框的显示与隐藏
      picDialogVisible: false,
      // 图片的url地址
      picPath: ''
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    async getCateList() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      // this.$message.success(res.meta.msg)
      this.cateList = res.data
      // console.log(res.data)
    },
    // 级联选择器选中项变化时触发
    handleChange() {
      // console.log(this.addForm.goods_cat)
      if (this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat = []
      }
    },

    // tab 栏 切换时触发
    changeTabs(active, oldactive) {
      // console.log(active, oldactive)
      if (oldactive === '0' && this.addForm.goods_cat.length !== 3) {
        this.$message.error('请选择分类！ ')
        return false
      } else if (oldactive === '1' && this.addForm.goods_cat.length !== 3) {
        this.$message.error('请选择分类！ ')
        return false
      }
    },

    // tab 栏被点击选中时触发
    async clickTabs() {
      // console.log(this.active)
      if (this.active === '1') {
        const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, { params: { sel: 'many' } })
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)

        // 处理数据
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals.length === 0 ? [] : item.attr_vals.split(' ')
        })
        this.manyData = res.data
        console.log(this.manyData)
      }

      if (this.active === '2') {
        const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, { params: { sel: 'only' } })
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        // res.data.forEach(item => {
        //   item.attr_vals = item.attr_vals.length === 0 ? [] : item.attr_vals.split(' ')
        // })
        this.onlyData = res.data
        console.log(this.onlyData)
      }
    },

    // 处理展示图片
    handlePreview(file) {
      this.picPath = file.response.data.url
      this.picDialogVisible = true
    },

    // 处理删除图片
    handleRemove(file) {
      // 获取删除的图片的 path 地址
      const filePath = file.response.data.tmp_path
      // 将数组中对应的图片地址 删掉 （ 使用过滤方法 ）
      this.addForm.pics = this.addForm.pics.filter(item => {
        return item.pic !== filePath
      })
    },

    // 图片上传成功后触发此方法 ，参数 response 为请求成功后 返回的数据
    successhandle(response) {
      // console.log(response)
      // 根据接口文档的要求来处理 数据。 将数据整理成上传时 需要 整理成的 格式
      const picInfo = { pic: response.data.tmp_path }
      this.addForm.pics.push(picInfo)
      console.log(this.addForm.pics)
    },

    // 添加商品
    addFormHandle() {
      this.manyData.forEach(item => {
        const Info = {
          attr_id: item.attr_id,
          attr_value: item.attr_vals.join(' ')
        }
        this.addForm.attrs.push(Info)
      })
      this.onlyData.forEach(item => {
        const Info = {
          attr_id: item.attr_id,
          attr_value: item.attr_vals
        }
        this.addForm.attrs.push(Info)
      })
      const Form = { ...this.addForm }
      Form.goods_cat = Form.goods_cat.join(',')
      // console.log(Form)
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post('goods', Form)
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.$router.push('/goods')
      })
    }
  },
  computed: {
    cateId() {
      if (this.addForm.goods_cat.length === 3) {
        return this.addForm.goods_cat[2]
      } else {
        return null
      }
    }
  }
}
</script>

<style lang="less" scoped>
.el-steps {
  margin: 40px;
}
.sbhh {
  width: 100%;
}
/deep/ .ql-editor {
  min-height: 300px;
}
</style>
